import datetime
import os.path
import time
import json
import requests
from libs.comps.common.component import manager , TComponentManager , TComponent

from libs.utils.tdb_utils import TTDB


class TCompTDB( TComponent):
    def __init__(self, _manager):
        super().__init__(_manager)
        self.pool = None
        self.handlers = {
            "query": self.query,
        }
    @property
    def host(self):
        return self.compSettings['host'] if "host" in self.compSettings.keys() else ""
    @property
    def port(self):
        return self.compSettings['port'] if "port" in self.compSettings.keys() else 1883
    @property
    def token(self):
        return self.compSettings['token'] if "token" in self.compSettings.keys() else ""
    @property
    def db(self):
        return self.compSettings['db'] if "db" in self.compSettings.keys() else ""

    def tdbQuerySuccess(self, queryResult):
        res = 0
        try:
            if( 'results' in queryResult.keys() and len(queryResult['results'])>0 ):
                if ('series' in  (queryResult['results'][0]).keys() ):
                    res = len(queryResult['results'][0]['series'])
        except Exception as er:
            print('tdb query success fail')
        return  res
    def tdbQuerySeries(self, queryResult):
        res = []
        try:
            series = queryResult['results'][0]['series']
            for ser in series:
                if "values" in ser.keys():
                    dictCol = ser['columns']
                    item = [dict(zip(dictCol , x)) for x in ser['values']]
                else:
                    item=[]
                res.append(item)
        except Exception as er:
            print('tdb query success fail')
        return  res

    def query(self , sql ):
        res={
            "status":0 ,
            "result":None
        }
        try:
            headers = {
                "Authorization": self.token,
                'Content-Type': 'application/json',
            }
            influxdb_url = "http://" + self.host + ":" + str(self.port) + '/query?db=' + self.db
            influxdb_url += "&q="+sql
            resp = requests.post(url=influxdb_url, headers=headers)
            if resp.status_code in [200]:
                try:
                    queryResult = json.loads(resp.text)
                    flag = self.tdbQuerySuccess(queryResult)
                    if flag :
                        res['result'] = self.tdbQuerySeries(queryResult)
                        res['status'] = 1
                except Exception as erresp:
                    self.manager.log(self , erresp)
        except Exception as er:
            print(er)
        return res
    def querySeries(self , sql ):
        res={
            "status":0 ,
            "result":None
        }
        try:
            headers = {
                "Authorization": self.token,
                'Content-Type': 'application/json',
            }
            influxdb_url = "http://" + self.host + ":" + str(self.port) + '/query?db=' + self.db
            influxdb_url += "&q="+sql
            resp = requests.post(url=influxdb_url, headers=headers)
            if resp.status_code in [200]:
                try:
                    queryResult = json.loads(resp.text)
                    flag = self.tdbQuerySuccess(queryResult)
                    if flag :
                        series ={}
                        serRes = queryResult['results'][0]['series']
                        for ser in serRes:
                            series[ser['name']] = {
                                "columns":ser['columns'] if 'columns'  in ser.keys() else []
                            }
                            rows=[]
                            if "values" in ser.keys():
                                dictCol = ser['columns']
                                rows = [dict(zip(dictCol, x)) for x in ser['values']]
                            series[ser['name']]['rows'] = rows
                        res['result'] = series
                        res['status'] = 1
                except Exception as erresp:
                    self.manager.log(self , erresp)
        except Exception as er:
            print(er)
        return res
    def getContinueQueries(self ):
        res={
            "status":0 ,
            "result":[]
        }
        try:
            queryRes = self.querySeries('SHOW CONTINUOUS QUERIES')
            if queryRes['status']==1:
                if self.db in queryRes['result']:
                    res['result'] =[
                        {"name":x['name'] , "query":x['query']}
                    for x in  queryRes['result'][self.db]['rows']]
            res['status'] = 1
        except Exception as er:
            print(er)
        return res
manager.registCompType("TCompTDB", TCompTDB)